import UserTables from "../tables/UserTables";
import ResMethod from "../utils/ResMethod";
import { useEffect, useState } from "react";
import { Select, Input, Button, message, Modal, Form } from "antd";

const UserList: React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();

  async function getUserData() { 
    const data = await ResMethod("/user", "GET");
    if (data) {
      if (data === 401) {
        messageApi.info({
          type: "error",
          content: "登录过期，请重新登录",
        });
        setTimeout(() => {
          window.location.href = "/login";
        }, 400);
      } else {
        setUserData(data);
      }
    }
  }

  const Suinfo = () => {
    messageApi.info({
      type: "success",
      content: "操作成功",
    });
  };

  const Errinfo = () => {
    messageApi.info({
      type: "error",
      content: "操作失败",
    });
  };

  const OnRoleSelected = (value: string) => {
    setRoleSelected(value);
  };

  const OnLevelSelected = (value: string) => {
    setLevelSelected(value);
  };

  const [name, setName] = useState("");
  const [roleSelected, setRoleSelected] = useState("学生");
  const [levelSelected, setLevelSelected] = useState("1");
  const [from_place, setFrom_place] = useState("");

  const filterUserData = async () => {
    const parma: object = {
      name: name,
      role: roleSelected,
      level: levelSelected,
      from_place: from_place,
    };

    const data = await ResMethod("/user", "GET", parma);
    console.log(data);
    if (data != "err") {
      Suinfo();
      return setUserData(data);
    } else {
      Errinfo();
    }
  };

  const deleteUser = async (name: string) => {
    const data = await ResMethod(`/user/${name}`, "DELETE");
    if (data) {
      Suinfo();
      getUserData();
    } else {
      Errinfo();
    }
  };

  const updateUser = async (values: any) => {
    const data = await ResMethod(`/user`, "PUT", values);
    if (data) {
      Suinfo();
      getUserData();
    } else {
      Errinfo();
    }
  };

  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    const values = await form.validateFields(); // 获取表单数据

    console.log(values);

    const res = await ResMethod("/user", "POST", values);

    if (res) {
      Suinfo();
      setIsModalOpen(false);
      getUserData();
    } else {
      Errinfo();
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const [userData, setUserData] = useState([
    {
      id: 1,
      name: "加载中",
      role: "",
      level: 0,
      last_login: "2025-01-01 12:00:00",
      active: false,
      from_place: "server",
    },
  ]);

  useEffect(() => {
    getUserData();
  }, []);

  return (
    <div className="h-full flex flex-col jusetify-center p-12 w-full">
      {contextHolder}
      <div className="flex flex-row items-center w-full">
        <span className="mr-3 font-normal text-md">用户名</span>
        <Input
          placeholder="请输入用户名"
          className="max-w-45"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

        <span className="mx-3 font-normal text-md">用户角色</span>
        <Select
          defaultValue="学生"
          style={{ width: 120 }}
          onChange={OnRoleSelected}
          options={[
            { value: "学生", label: "学生" },
            { value: "教师", label: "教师" },
            { value: "职工", label: "职工" },
            { value: "校外人员", label: "校外人员" },
          ]}
        />

        <span className="mx-3 font-normal text-md">用户权限</span>
        <Select
          defaultValue="1"
          style={{ width: 200 }}
          onChange={OnLevelSelected}
          options={[
            { value: "0", label: "0 - 访客" },
            { value: "1", label: "1 - 普通学生/兼职人员" },
            { value: "2", label: "2 - 骨干学生/校内&周边商户" },
            { value: "3", label: "3 - 教师/行政/职工" },
            { value: "4", label: "4 - 管理员" },
          ]}
        />

        <span className="mx-3 font-normal text-md">归属部门</span>
        <Input
          placeholder="请输入归属部门"
          className="max-w-50"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

        <Button type="primary" className="ml-3" onClick={filterUserData}>
          查询
        </Button>
        <Button className="ml-3" onClick={showModal}>
          新增
        </Button>
      </div>
      <div className="mt-5">
        <Modal
          title="新增用户"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          okText={"确定"}
          cancelText={"取消"}
        >
          <Form form={form} layout="vertical">
            <Form.Item
              name="name"
              label="用户名"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="role"
              label="用户角色"
              rules={[{ required: true, message: "请选择用户角色" }]}
            >
              <Select>
                <Select.Option value="学生">学生</Select.Option>
                <Select.Option value="教师">教师</Select.Option>
                <Select.Option value="职工">职工</Select.Option>
                <Select.Option value="校外人员">校外人员</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="user"
              label="用户账号"
              rules={[{ required: true, message: "请输入用户账号" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="password"
              label="用户密码"
              rules={[{ required: true, message: "请输入用户密码" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="from_place"
              label="归属部门"
              rules={[{ required: true, message: "请输入归属部门" }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        <UserTables
          dataSource={userData}
          onDelete={deleteUser}
          onUpdate={updateUser}
        />
      </div>
    </div>
  );
};

export default UserList;
